package com.hh.workflow.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.task.Attachment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hh.baseframework.util.check.Check;
import com.hh.system.util.file.FileUpload;
import com.hh.workflow.mode.User;
import com.hh.workflow.service.inf.IUserService;

@Service
public class FileService extends ActivitiService {
	@Autowired
	private IUserService loginUserUtilService;
	@Autowired
	private IUserService userService;

	public Attachment save(String type, String name, String filePath,
			File attachment, String attachmentFileName, String taskId,
			String piid) {
		String path = FileUpload.uploadFile(attachment, attachmentFileName,
				filePath);
		identityService.setAuthenticatedUserId(loginUserUtilService
				.findLoginUserId());
		Attachment attachment2 = taskService.createAttachment(type, taskId, piid, name,
				attachmentFileName, path);
		return attachment2;
	}

	public List<Map<String, Object>> queryAttachmentPiid(String piid) {
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		List<Attachment> attachmentList = taskService
				.getProcessInstanceAttachments(piid);
		for (Attachment attachment : attachmentList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", attachment.getId());
			map.put("type", attachment.getType());
			map.put("name", attachment.getDescription());
			map.put("attachmentFileName", attachment.getName());
			map.put("path", attachment.getUrl());
			if (Check.isNoEmpty(attachment.getUserId())) {
				User user = userService.findUserById(attachment.getUserId());
				map.put("userName", user.getText());
				map.put("userId", attachment.getUserId());
			}
			map.put("taskId", attachment.getTaskId());
			mapList.add(map);
		}
		return mapList;
	}

	public void delete(String id) {
		taskService.deleteAttachment(id);
	}

	public Object queryAttachmentTaskId(String taskId) {
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		List<Attachment> attachmentList = taskService.getTaskAttachments(taskId);
		for (Attachment attachment : attachmentList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", attachment.getId());
			map.put("type", attachment.getType());
			map.put("name", attachment.getDescription());
			map.put("attachmentFileName", attachment.getName());
			map.put("path", attachment.getUrl());
			if (Check.isNoEmpty(attachment.getUserId())) {
				User user = userService.findUserById(attachment.getUserId());
				map.put("userName", user.getText());
				map.put("userId", attachment.getUserId());
			}
			map.put("taskId", attachment.getTaskId());
			mapList.add(map);
		}
		return mapList;
	}
}
